package com.admin.oauth;

import com.admin.common.utils.EncryptUtils;
import com.admin.common.utils.PageResult;
import com.admin.component.web.MultipartFileUtil;
import com.admin.oauth.component.OnlineUserComponent;
import com.admin.oauth.component.UserCacheManager;
import com.admin.oauth.dto.OnlineUserDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author sq-lan
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/auth/online")
@Api(tags = "系统：在线用户管理")
public class OnlineController {

    @Resource
    private OnlineUserComponent onlineUserComponent;
    @Resource
    private UserCacheManager userCacheManager;

    @ApiOperation("在线用户")
    @GetMapping
    @PreAuthorize("@ss.check()")
    public ResponseEntity<PageResult<OnlineUserDto>> paging(String username, Pageable pageable) {
        return new ResponseEntity<>(onlineUserComponent.list(username, pageable), HttpStatus.OK);
    }

    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@ss.check()")
    public void export(HttpServletResponse response, String username) throws IOException {
        List<OnlineUserDto> list = onlineUserComponent.list(username);
        List<Map<String, Object>> result = new ArrayList<>();
        for (OnlineUserDto user : list) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("用户名", user.getUserName());
            map.put("部门", user.getDept());
            map.put("登录IP", user.getIp());
            map.put("登录地点", user.getAddress());
            map.put("浏览器", user.getBrowser());
            map.put("登录日期", user.getLoginTime());
            result.add(map);
        }
        MultipartFileUtil.downloadExcel(result, response);
    }

    @ApiOperation("踢出用户")
    @DeleteMapping
    @PreAuthorize("@ss.check()")
    public ResponseEntity<Object> offline(@RequestBody Set<String> keys) throws Exception {
        for (String token : keys) {
            // 解密Key
            token = EncryptUtils.desDecrypt(token);
            userCacheManager.logout(token);
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
